/* 
 * StikiWeb Wiki - a Wiki for Hierarchical Organizations
 * $Id: EditPageAction.java,v 1.5 2004/05/05 05:23:43 biglee Exp $
 * 
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the StikiWeb Wiki.
 *
 * The Initial Developer of the Original Code is Lee Haslup (biglee@haslups.com).
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** 
 */
package org.stikiweb.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.stikiweb.contentMagnager.PageManager;
import org.stikiweb.contentMagnager.PermissionManager;
import org.stikiweb.translations.StikiWebTranslator;

/**
 * @author Allen L (BigLee) Haslup
 *
 */
public class EditPageAction extends StikiAction {

	/* (non-Javadoc)
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest req,
		HttpServletResponse resp)
		{
			setup(req);
			HttpSession session = req.getSession();
			PageBean pb = (PageBean)form;
			
			// if there is no input we don't know what page to edit so we fail.
			if(pb==null || pb.getName()==null) {
				return mapping.findForward("failure");
			}
			
			// decide where to go if we are leaving
			String returnTo = (String)session.getAttribute("currentPage");
			if(returnTo==null) {
				returnTo = "main";
			}
			
			// if the user hit cancel, just go display the current page.
			if(pb.getCancel()!=null) {
				/* why don't these statements work?? PageBean name property is getting set again from request.
				pb.setName(returnTo);
				return mapping.findForward("success");
				*/
				return new ActionForward("/viewPage.do?name="+returnTo, true);
			}
			
			// fetch the operation (create,edit, audit, comment)
			String op = pb.getOperation();
			if(op==null) {
				op="";
			} 
			else {
				op=op.trim();
			}
			boolean creating = "CREATE".equalsIgnoreCase(op);
			boolean editing = "EDIT".equalsIgnoreCase(op);
			boolean auditing = "AUDIT".equalsIgnoreCase(op);
			boolean commenting = "COMMENT".equalsIgnoreCase(op);
			
			// if there is no operation specified, go view the page
			if(!(creating||editing||auditing||commenting)) {
				return new ActionForward("/viewPage.do?name="+returnTo,true);
			}
			
			// do a few checks to see if we can perform the operation
			try {
				PageManager pm = PageManager.solo();
				String name = pb.getName();
				
				// if the page doesn't exist and we are not creating we fail.
				if(!pm.pageExists(name) && !creating){
					return mapping.findForward("failure");
				}
				
				// if we don't have the permission to perform the operation...
				PermissionManager permM = PermissionManager.solo();
				String userName = getUserName(req);
				int permLevel = permM.userPermLevelForPage(userName,name);
				int pPermLevel = permM.userPermLevelForParentPage(userName,name);
				
				if( (creating && pPermLevel < PermissionManager.EXTEND)
					|| (editing && permLevel < PermissionManager.EDIT)
					|| (auditing && permLevel < PermissionManager.AUDIT)
					|| (commenting && permLevel < PermissionManager.COMMENT))
				{
					// ... and we are logged in, fail.
					if(this.isLoggedIn(req)) {
						return mapping.findForward("failure");
					}
					// if we are not logged in, try logging in and see if that helps.
					else {
						return goLoginFirst("editPage", op, name,req);
					}
				}
				
				// at this point we've done our checks and we can perform the operation.
				String markup = pb.getNewMarkup();
				String commentHeading = "";
				if(commenting) {
					String guestName = permM.getGuestName(req);
					commentHeading = "\n\n__[[ ["
						+userName
						+(guestName.length()>0?(" ("+guestName+")"):"")
						+"|UserProfiles."
						+userName
						+"] ]__\n\n";
				}
				// If we are saving, do so and return success
				if(pb.getSave()!=null) {
					if(commenting) {
						String existingMarkup = pm.getPage(name);
						markup = existingMarkup 
							+ commentHeading 
							+ markup;
					}
					pm.savePage(name,markup);
					return new ActionForward("/viewPage.do?name="+name,true);
				}
				// if we are previewing, translate the page and go back to the
				// editing form
				if(pb.getPreview()!=null) {
					if(commenting) {
						markup = commentHeading 
						+ markup;
					}
					pb.setText(new StikiWebTranslator().translateText(markup,name, name, req));
					return new ActionForward(mapping.getInput());
				}
				// we are just starting a new edit.  Fetch the markup
				if(creating || commenting) {
					pb.setNewMarkup("");
				}
				else {
					pb.setNewMarkup(pm.getPage(name));
				}
				// remember where we are but don't set to a page not yet created.
				if(!creating) {
					session.setAttribute("currentPage",name);
				} 
				return new ActionForward(mapping.getInput());
			}
			catch(Exception e) {
				return mapping.findForward("failure");
		}
	}
}
